package org.chen.wordwave.base.ui;

import static org.chen.wordwave.act.Main.iconArray;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.hjq.toast.Toaster;

import org.chen.wordwave.R;
import org.chen.wordwave.init.WordInit;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class LuckyView extends ConstraintLayout {
    private View[] lotteryArray;
    private ValueAnimator animator = new ValueAnimator();
    private int luckyIndex = -1;
    private DrawListener drawListener;
    private final Map<Integer, Double> probabilityMap = new HashMap<>();
    public LuckyView(Context context) {
        super(context);
        init(context);
    }
    public LuckyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public LuckyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }
    private String getPrizeName(int index) {
        switch (index) {
            case 0:
                return getContext().getString(R.string.points_10);
            case 1:
                return getContext().getString(R.string.points_50);
            case 2:
                return getContext().getString(R.string.points_100);
            case 3:
                return getContext().getString(R.string.discount_20);
            case 4:
            case 7:
                return getContext().getString(R.string.thanks_for_participating);
            case 5:
                return getContext().getString(R.string.points_200);
            case 6:
                return getContext().getString(R.string.points_300);
            default:
                return getContext().getString(R.string.unknown_prize);
        }
    }

    public void setDrawListener(DrawListener listener) {
        this.drawListener = listener;
    }

    public interface DrawListener {
        void onDrawComplete(String prize);
        int getUserLotteryCount();
    }
    private void init(Context context) {
        inflate(context, R.layout.lucky_draw, this);
        lotteryArray = new View[]{
                findViewById(R.id.include_lottery0),
                findViewById(R.id.include_lottery1),
                findViewById(R.id.include_lottery2),
                findViewById(R.id.include_lottery3),
                findViewById(R.id.include_lottery4),
                findViewById(R.id.include_lottery5),
                findViewById(R.id.include_lottery6),
                findViewById(R.id.include_lottery7)
        };
        animator.setDuration(3000);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.addUpdateListener(animation -> {
            int position = (int) animation.getAnimatedValue();
            setCurrentPosition(position % 8);
        });
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                setCurrentPosition(luckyIndex);
                if (drawListener != null) {
                    drawListener.onDrawComplete(getPrizeName(luckyIndex));
                }
            }
        });


        setupProbabilityMap();

        if (WordInit.language.equals("zh")){
            setLotteryInfo(R.mipmap.icon_lottery);
        }else {
            setLotteryInfo(R.mipmap.icon_lottery_en);
        }

    }
    private void setupProbabilityMap() {
        probabilityMap.put(0, 0.15); // 15%
        probabilityMap.put(1, 0.10); // 10%
        probabilityMap.put(2, 0.05); // 5%
        probabilityMap.put(3, 0.30); // 30%
        probabilityMap.put(4, 0.15); // 15%
        probabilityMap.put(5, 0.025); // 2.5%
        probabilityMap.put(6, 0.025); // 2.5%
        probabilityMap.put(7, 0.20); // 20%
    }

    private void setCurrentPosition(int position) {
        // 刷新当前所在位置
        for (int index = 0; index < lotteryArray.length; index++) {
            View view = lotteryArray[index];
            view.findViewById(R.id.view_shadow).setVisibility(index == position ? View.GONE : View.VISIBLE);
        }
    }

    public void setLotteryInfo(int btn) {
        this.luckyIndex = getLuckyIndex();
        setLotteryBtn(btn);
        for (int index = 0; index < lotteryArray.length; index++) {
            setLotteryItem(lotteryArray[index], index);
        }
        animator.setIntValues(0, 2 * 8 + luckyIndex);
    }

    private int getLuckyIndex() {
        double randomValue = new Random().nextDouble();
        double cumulativeProbability = 0.0;
        for (Map.Entry<Integer, Double> entry : probabilityMap.entrySet()) {
            cumulativeProbability += entry.getValue();
            if (randomValue <= cumulativeProbability) {
                return entry.getKey();
            }
        }
        return 4; // 默认值设置为“谢谢参与”
    }

    private void setLotteryItem(View view, int position) {
        ((ImageView) view.findViewById(R.id.iv_lottery)).setImageResource(iconArray[position]);
        ((TextView) view.findViewById(R.id.tv_lottery_name)).setText(getPrizeName(position));
    }
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
    }
    @SuppressLint({"ShowToast", "CutPasteId"})
    private void setLotteryBtn(int btn) {
        findViewById(R.id.include_button).findViewById(R.id.iv_lottery).setVisibility(View.GONE);
        findViewById(R.id.include_button).findViewById(R.id.tv_lottery_name).setVisibility(View.GONE);
        findViewById(R.id.include_button).findViewById(R.id.iv_bg).setBackgroundResource(btn);
        findViewById(R.id.include_button).setOnClickListener(v -> {
            // 重新计算幸运索引
            setLotteryInfo(btn);
            // 开始动画
            if (drawListener != null && drawListener.getUserLotteryCount() > 0){
                animator.start();
            }else {
                Toaster.show(getContext().getString(R.string.use_empty));
            }

        });
    }
}
